<template>
  <div class="chart-container">
    <canvas ref="chartCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import Chart from 'chart.js/auto'

// 只调用一次 defineProps，使用对象语法
const props = defineProps({
  heartData: {
    type: Array,
    default: () => []
  },
  breathData: {
    type: Array,
    default: () => []
  },
  timeLabels: {
    type: Array,
    default: () => []
  }
})

const chartCanvas = ref(null)
let chartInstance = null

const initChart = () => {
  if (chartCanvas.value) {
    const ctx = chartCanvas.value.getContext('2d')
    chartInstance = new Chart(ctx, {
      type: 'line',
      data: {
        labels: props.timeLabels,
        datasets: [
          {
            label: '心率',
            data: props.heartData,
            borderColor: '#e74c3c',
            backgroundColor: 'rgba(231, 76, 60, 0.1)',
            tension: 0.4,
            fill: true
          },
          {
            label: '呼吸',
            data: props.breathData,
            borderColor: '#3498db',
            backgroundColor: 'rgba(52, 152, 219, 0.1)',
            tension: 0.4,
            fill: true
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: false,
            title: {
              display: true,
              text: '数值'
            }
          },
          x: {
            title: {
              display: true,
              text: '时间'
            }
          }
        }
      }
    })
  }
}

const updateChart = () => {
  if (chartInstance) {
    chartInstance.data.labels = props.timeLabels
    chartInstance.data.datasets[0].data = props.heartData
    chartInstance.data.datasets[1].data = props.breathData
    chartInstance.update()
  }
}

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.destroy()
  }
})

watch(
  () => [props.heartData, props.breathData, props.timeLabels],
  () => {
    updateChart()
  },
  { deep: true }
)
</script>

<style scoped>
.chart-container {
  position: relative;
  height: 300px;
  width: 100%;
}
</style>
